use std::io::{self, Write};

fn convert_to_decimal(num: &str, base: i32) -> i32 {
    let mut decimal_value = 0;
    let mut power = 1;  // 从最低位开始计算

    // 从右到左遍历字符串，计算每个位置的数字值
    for ch in num.chars().rev() {
        let digit = match ch {
            '0'..='9' => ch.to_digit(10).unwrap() as i32,
            'a'..='f' => ch.to_digit(16).unwrap() as i32 - 10,
            'A'..='F' => ch.to_digit(16).unwrap() as i32 - 10,
            _ => panic!("Invalid character in input"),
        };

        if digit >= base {
            panic!("Digit {} is not valid for base {}", ch, base);
        }

        decimal_value += digit * power;
        power *= base;
    }

    decimal_value
}

fn convert_from_decimal(num: i32, base: i32) -> String {
    if num == 0 {
        return "0".to_string();
    }

    let mut result = String::new();
    let mut num = num;

    while num > 0 {
        let remainder = num % base;
        let digit = if remainder < 10 {
            (b'0' + remainder as u8) as char
        } else {
            (b'a' + (remainder - 10) as u8) as char
        };
        result.push(digit);
        num /= base;
    }

    result.chars().rev().collect()
}

fn convert_base_1(num: &str, from_base: i32, to_base: i32) -> String {
    // Step 1: Convert from 'from_base' to decimal
    let decimal_value = convert_to_decimal(num, from_base);

    // Step 2: Convert from decimal to 'to_base'
    convert_from_decimal(decimal_value, to_base)
}

fn parse_input(input: &str) -> (String, i32) {
    // 解析输入格式 "1111(2)"
    let num_and_base = input.trim();  // 去除两端的空白字符

    // 查找括号的位置，获取数字和源进制
    let num_end_pos = num_and_base.find('(').unwrap();
    let num = num_and_base[..num_end_pos].to_string();  // 提取数字部分
    let from_base: i32 = num_and_base[num_end_pos + 1..num_and_base.len() - 1]  // 提取进制
        .parse()
        .unwrap();

    (num, from_base)
}





pub fn convert_base(num_str: &str, to_base: u32) -> String {
    // TODO: 这里写逻辑
     // 解析输入
    let (num, from_base) = parse_input(&num_str);

    // 确保进制在有效范围内
    if from_base < 2 || from_base > 16 || to_base < 2 || to_base > 16 {
        println!("进制必须在 2 到 16 之间！");
        
    }
    
    let to_base_1: i32 = to_base as i32;

    // 执行进制转换
    let result = convert_base_1(&num, from_base, to_base_1);
    
    result
    
    
    
}
